//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.WindowsPhoneChat.Commands
{
    using System;
    using Microsoft.Samples.ServiceBus.Messaging;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.ViewModels;

    public class DeleteTopicCommand : AsyncCommand<ChatTopicViewModel>
    {
        protected override bool CanExecute(ChatTopicViewModel viewModel)
        {
            return viewModel != null;
        }

        protected override void Execute(ChatTopicViewModel viewModel)
        {
            TopicClient.BeginDeleteTopic(viewModel.TopicClient.Path, App.Context.TokenProvider, this.OnDeleteTopicCompleted, viewModel);
        }

        private void OnDeleteTopicCompleted(IAsyncResult result)
        {
            // Retrieve the topic's view model from the async state
            var viewModel = (ChatTopicViewModel)result.AsyncState;

            try
            {
                // end the async call to remove subscription - if the call failed, an exception will
                // be thrown
                TopicClient.EndDeleteTopic(result);

                // update the view model to indicate that there is no longer an active subscription
                // to this topic - this will result in the 'star' next to the topic becoming greyed
                // out and receives on the subscription to end
                viewModel.Dispatcher.BeginInvoke(() =>
                    {
                        viewModel.Owner.Remove(viewModel);
                        this.OnExecuteCompleted(viewModel);
                    });
            }
            catch (Exception e)
            {
                App.ShowError(e);
                this.OnExecuteCompleted(viewModel, true);
            }
        }
    }
}
